﻿	

#region Using Directives
using System;
using System.ComponentModel;
using System.Collections;
using System.Xml.Serialization;
using System.Data;

using NetROS.Tiers.Entities;
using NetROS.Tiers.Entities.Validation;

using NetROS.Tiers.Data;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using NetROS.Tiers.Services;
using NetROS.Tiers.Processors;
using NetROS.Tiers.Data.Bases;

#endregion

namespace NetROS.Tiers.Services
{		
	
	///<summary>
	/// An component type implementation of the 'tblDokument' table.
	///</summary>
	/// <remarks>
	/// All custom implementations should be done here.
	/// </remarks>
	[CLSCompliant(true)]
	public partial class DokumentService : NetROS.Tiers.Services.DokumentServiceBase
	{
		/// <summary>
		/// Initializes a new instance of the DokumentService class.
		/// </summary>
		public DokumentService() : base()
		{
		}


        public Dokument SaveKontrolomKolicine(Dokument entity)
        {

 TransactionManager transactionManager = null;

 try
 {
     bool isBorrowedTransaction = ConnectionScope.Current.HasTransaction;

     //since this is a read operation, don't create a tran by default, only use tran if provided to us for custom isolation level
     transactionManager = ConnectionScope.ValidateOrCreateTransaction();
     
     NetTiersProvider dataProvider = ConnectionScope.Current.DataProvider;

     //Persist Entity

    

     VwArtiklStanjeuSkladistuService vwArtServView = new VwArtiklStanjeuSkladistuService();
     bool Error = false;
     foreach (DokumentStavka tmpstavka in entity.DokumentStavkaCollection)
     {
         //if (entity.ID != 0 && entity.ID != tmpstavka.IDDokument)
         //{
             //tmpstavka.IDDokument = entity.ID;
         //}
         VwArtiklStanjeuSkladistuParameterBuilder vwaspb = new VwArtiklStanjeuSkladistuParameterBuilder();    
       //  tmpstavka.IDDokumentSource = entity;
         vwaspb.AppendEquals(VwArtiklStanjeuSkladistuColumn.IDOrganizacijaOd, entity.IDOrganizacijaOd.ToString());
         vwaspb.AppendEquals(VwArtiklStanjeuSkladistuColumn.IDArtikl, tmpstavka.IDArtikl.ToString());

         VList<VwArtiklStanjeuSkladistu> tmpskladiste = vwArtServView.Find(vwaspb.GetParameters());
         if (tmpskladiste.Count != 0)
         {
             TList<DokumentStavka> tmArtikli = entity.DokumentStavkaCollection.FindAll(DokumentStavkaColumn.IDArtikl, tmpstavka.IDArtikl);
             float Kolicina = 0;

             foreach (DokumentStavka tmpArtikl in tmArtikli)
             {
                 Kolicina += tmpArtikl.Kolicina;
             }

             if ((tmpskladiste[0].Stanje - Kolicina) < 0)
             {
                 double? Loc = tmpskladiste[0].Stanje;
                 tmpstavka.AddValidationRuleHandler((delegate(object target, ValidationRuleArgs e) {
                     NetROS.Tiers.Entities.Validation.CommonRules.CompareValueRuleArgs<double?> _loce = (e as NetROS.Tiers.Entities.Validation.CommonRules.CompareValueRuleArgs<double?>);
                     System.Reflection.PropertyInfo p = target.GetType().GetProperty(e.PropertyName);

                     float? value;
                      try
                {
                    value = (float?)p.GetValue(target, null);
                }
                catch (Exception)
                {
                    return true;
                }
                     if ((_loce.CompareValue - value) <0)
                 {
                     e.Description = String.Format("Greška nedovoljna količina stanje {0}",_loce.CompareValue); return false; 
                        }
                     else
                     {
                         return true;
                     }
                 }), new NetROS.Tiers.Entities.Validation.CommonRules.CompareValueRuleArgs<double?>("Kolicina", Loc));
                 tmpstavka.Validate();
                 Error = true;
             }
         }
         else
         {
             Error = true;
         }
     }
     if (Error)
     {
         if (transactionManager != null && transactionManager.IsOpen)
             transactionManager.Rollback();
         return null;
     }

     dataProvider.DokumentProvider.Save(transactionManager, entity);

     foreach (DokumentStavka tmpstavka in entity.DokumentStavkaCollection)
     {
         //if (entity.ID != 0 && entity.ID != tmpstavka.IDDokument)
         //{
         tmpstavka.IDDokument = entity.ID;
     }
      dataProvider.DokumentStavkaProvider.Save(transactionManager,entity.DokumentStavkaCollection);

     //if persisted and tran not borrowed, commit
     if (!isBorrowedTransaction && transactionManager != null && transactionManager.IsOpen)
         transactionManager.Commit();
 }
 catch (Exception exc)
 {
     //if open, rollback
     if (transactionManager != null && transactionManager.IsOpen)
         transactionManager.Rollback();

     //Handle exception based on policy
     if (DomainUtil.HandleException(exc, "NoneExceptionPolicy"))
         throw;
 }

            return entity;

            ////ProcessorList.Add(new PostojeArtikliNaSkladistu(Entity));
            ////ProcessorList.Add(new SavePrijemniList(Entity));
            //TransactionManager tm = null;

            //try
            //{
            //    tm = ConnectionScope.ValidateOrCreateTransaction(true);
            //    ServiceResult result = this.Execute(true);
            //    if (result.HasErrors)
            //    {
            //        throw new Exception(result.Error.ToString());
            //    }
            //    else
            //    {
            //        tm.Commit();
            //    }
            //    return !result.HasErrors;
                
            //}
            //catch (Exception ex)
            //{
            //    tm.Rollback();
            //    throw ex;
            //}


        }

		
	}//End Class


} // end namespace


namespace NetROS.Tiers.Processors
{
    public class PostojeArtikliNaSkladistu : ProcessorBase
    {
        private Dokument Entity;
        private GenericProcessorResult genericProcessorResult;


        public PostojeArtikliNaSkladistu(Dokument entity)
        {
            if (entity == null) throw new ArgumentNullException("Dokument je null");
            if (entity.DokumentStavkaCollection == null) throw new ArgumentNullException("DokumentStavka u dokumentu je null");
            this.Entity = entity;
        }

        public override IProcessorResult Process()
        {
            try
            { ///Add custom validation rules for this processor order.AddInventoryRules();
                foreach (DokumentStavka tmp in Entity.DokumentStavkaCollection)
                {
                    tmp.AddValidationPrijemniList();
                    tmp.Validate();
                }
               bool res=  Entity.DokumentStavkaCollection.IsValid;
                Entity.Validate();
                if (Entity.IsValid) ProcessResult.AddBrokenRulesList(typeof(Dokument), Entity.BrokenRulesList);
            }
            catch (Exception exc) { if (DomainUtil.HandleException(exc, "NoneExceptionPolicy")) throw; }

            return ProcessResult;
        } 
        public override IProcessorResult ProcessResult
        {
            get
            {
                if (genericProcessorResult == null)
                { genericProcessorResult = new GenericProcessorResult(); }
                return genericProcessorResult;
            }
        }
    }


    public class SavePrijemniList : ProcessorBase
    {
        private Dokument Entity;
        private GenericProcessorResult genericProcessorResult;
        private DokumentService Servis = new DokumentService();


        public SavePrijemniList(Dokument entity)
        {
            if (entity == null) throw new ArgumentNullException("Dokument je null");
            if (entity.DokumentStavkaCollection == null) throw new ArgumentNullException("DokumentStavka u dokumentu je null");
            this.Entity = entity;
        }

        public override IProcessorResult Process()
        {
            try
            { ///Add custom validation rules for this processor order.AddInventoryRules();

                //Servis.DeepSave(Entity, NetROS.Tiers.Data.DeepSaveType.IncludeChildren, typeof(TList<DokumentStavka>));
              Servis.Save(Entity);
                //foreach (DokumentStavka tmpstavka in Entity.DokumentStavkaCollection)
                //{
                //    tmpstavka.IDDokument = Entity.ID;
                //}
                //DokumentStavkaService tmpser = new DokumentStavkaService();
                //tmpser.Save(Entity.DokumentStavkaCollection);
            }
            catch (Exception exc) { if (DomainUtil.HandleException(exc, "NoneExceptionPolicy")) throw; }

            return ProcessResult;
        }
        public override IProcessorResult ProcessResult
        {
            get
            {
                if (genericProcessorResult == null)
                { genericProcessorResult = new GenericProcessorResult(); }
                return genericProcessorResult;
            }
        }
    }
}